package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.ParamMissException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

import static com.sky.constant.MessageConstant.PARAMS_MISSED;
import static com.sky.constant.PasswordConstant.DEFAULT_PASSWORD;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        //password进行MD5加密
        //String secretPwd02=org.springframework.util.DigestUtils.md5Digest();
        //String secretPwd=DigestUtils.md5Digest(password); 错误原因 倒错了
        String secretPwd = DigestUtils.md5Hex(password);
        


        if (!secretPwd.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    @Override
    public int insertEmployee(EmployeeDTO employeeDTO) throws ParamMissException {
        //1.校验工作

        if (StringUtils.isBlank(employeeDTO.getUsername())||StringUtils.isBlank(employeeDTO.getPhone())){
            throw new ParamMissException("传入参数缺失！");
        }

        //2.讲employeeDTO交给employee对象
        Employee targetEmp = new Employee();
        BeanUtils.copyProperties(employeeDTO,targetEmp);//讲同名同类型属性进行赋值

        //3.设置密码，状态，创建日期巴拉巴拉；
        String hexPwd = DigestUtils.md5Hex(DEFAULT_PASSWORD);
        targetEmp.setPassword(hexPwd);
        targetEmp.setStatus(StatusConstant.ENABLE);
        targetEmp.setCreateTime(LocalDateTime.now());
        //TODO 登陆人是谁？
        Long empId = BaseContext.getCurrentId();
        targetEmp.setCreateUser(empId);
        targetEmp.setUpdateTime(LocalDateTime.now());
        targetEmp.setUpdateUser(empId);

        //新增员工
        int optCnt=employeeMapper.insertEmployee(targetEmp);
        return optCnt;
    }

    @Override
    public PageResult findPage(EmployeePageQueryDTO pageQuery) {
        //1.分页条件构建
        PageHelper.startPage(pageQuery.getPage(),pageQuery.getPageSize());
        //2.构建查询条件并SQL查询
        if (StringUtils.isNotBlank(pageQuery.getName())){
            pageQuery.setName("%"+pageQuery.getName()+"%");
        }
        //SQL执行 返回结果
        Page<Employee> employeePage=employeeMapper.findPage(pageQuery);

        long total = employeePage.getTotal();
        List<Employee> result = employeePage.getResult();

        return new PageResult(total,result);
    }

    @Override
    public int updateStatus(Integer status,Long id) throws ParamMissException {
        //更新员工(既可以更新状态也可以更新其他字段)
        if (id==null){
            throw new ParamMissException(PARAMS_MISSED);
        }
        Employee emp=new Employee();
        emp.setId(id);
        emp.setStatus(status);
        Employee employee=Employee.builder().id(id).status(status).build();
        int i=employeeMapper.updateStatus(employee);
        return i;
    }

    @Override
    public Employee findById(Long id) throws ParamMissException {
        if (id==null){
            throw new ParamMissException(PARAMS_MISSED);
        }
        Employee employee=employeeMapper.findById(id);
        employee.setPassword(null);
        return employee;
    }

    @Override
    public int updateEmpById(EmployeeDTO employeeDTO) throws ParamMissException {
        if (employeeDTO.getId()==null){
            throw new ParamMissException(PARAMS_MISSED);
        }
        Employee emp=new Employee();
        BeanUtils.copyProperties(employeeDTO,emp);
        emp.setUpdateTime(LocalDateTime.now());
        emp.setUpdateUser(BaseContext.getCurrentId());
        int i=employeeMapper.updateStatus(emp);
        return i;

    }

    @Override
    public int editPassword(PasswordEditDTO passwordEditDTO) {
        String password = DigestUtils.md5Hex(passwordEditDTO.getNewPassword());
        Employee emp = Employee.builder().id(passwordEditDTO.getEmpId()).password(password).build();
        int i=employeeMapper.updateStatus(emp);

        return i;
    }


}
